<?php
/**************************************************************************
	ESAM (EVE to SMF API Module)
	Copyright (C) 2009  Clinton Weiss

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

if (!defined('SMF')) die('Hacking attempt...');

require_once 'EsamGlobal.php';
require_once 'EsamAlliance.php';
require_once 'EsamQuery.php';
require_once 'EsamValidator.php';

function EsamProfileSettings() {
  global $context, $txt, $scripturl;

  $id_member =  $context['member']['id'];
  $esamQuery = new EsamQuery();
  $esamQuery->setQuery($esamQuery->Q_EVE_API);
  $esamQuery->setParameter("member_id", $id_member);
  $resultSet = $esamQuery->getResultSet();
  $row = count($resultSet) > 0 ? $resultSet[0] : array();

  $user_id = empty($row['USER_ID']) ? "" : $row['USER_ID'];
  $api_key = empty($row['API_KEY']) ? "" : $row['API_KEY'];

  displayApiTable($user_id, $api_key, $id_member);
}

function displayApiTable($user_id = "", $api_key = "", $member_id = null) {
  global $txt;

  $esamValidator = new EsamValidator();
  $esamGlobal = new EsamGlobal();

  $validApiKey = (empty($user_id) && empty($api_key)) ? false :  $esamValidator->checkUserAndKey($user_id, $api_key);

  // If this is the registration page, $member_id will be null
  // so no need to display the INVALID message here
  if ($member_id != null) {
    if ( $validApiKey == false) {
      echo "<p style='color: red; font-weight: bold;'>INVALID EVE API KEY</p>";
    }
  }
  if ( $esamGlobal->getGlobalSetting('GLOBAL_REQUIRED_API', "false") == "true" && $validApiKey == false) {
    echo "<p style='color: red; font-weight: bold;'>This site requires that you have a valid API Key entered.</p>";
  }

  echo "<b> " . $txt['eve_settings'] . "</b>
		<br /><br />
		<span style='float: left; width: 6em; font-weight: bold;'>User Id:</span>
		<input name='esamUserId' id='esamUserId' type='text' maxlength='8' size='12' value='$user_id'></input>
		<br /><br />
		<span style='float: left; width: 6em; font-weight: bold;'>API Key:</span>
		<input name='esamApiKey' id='esamApiKey' type='text' maxlength='64' size='85' value='$api_key'></input>
		<p>Don't know your API information?  Click <a href='http://www.eveonline.com/api/default.asp' target='_blank'>here</a> to get it.</p>
      ";


  if (!empty($user_id) && !empty($api_key) && !empty($member_id)) {
    $esamMembers = new EsamMembers();
    $usersPreferredChar = $esamMembers->getMemberSetting($member_id, "PREFERRED_CHAR_ID", "all");

    $eveApi = new EsamEveApi();
    $eveApi->setCredentials($user_id, $api_key);
    $data = $eveApi->getCharacters();
    if (!$eveApi->isError()) {
      $checked = ("all" == $usersPreferredChar ? "checked='true'" : "" );
      echo "<fieldset><legend>Select Main Character</legend>
							<input type='radio' name='esamMainChar' group='esamMainChar' value='all' $checked> Display All <br />
      ";

      $data = new SimpleXMLElement($data);
      foreach($data->result->rowset->row as $row) {
        $toonId = $row['characterID'];
        $toonName = $row['name'];
        $checked = ((string) $toonId == (string) $usersPreferredChar ? "checked='true'" : "" );
        echo "<input type='radio' name='esamMainChar' group='esamMainChar' value='$toonId' $checked> $toonName <br />";
      }
      echo "</fieldset>";
    }
  }

  echo "		<hr width='100%' size='1' class='hrcolor' />";
}

/**
 * Cleans up the passed string to prevent API injection
 */
function cleanup($string, $maxLength) {
  $string = stripslashes($string);
  $string = preg_replace("/[^A-Za-z0-9]*/", '', $string);
  $string = substr($string, 0, $maxLength);
  return $string;
}

function saveEsamApiChanges($id_member) {
  global $context;

  if (empty($id_member)) {
    fatal_lang("Invalid ID", false);
  }

  echo "Saving";

  if (isset($_POST['esamMainChar'])) {
    $esamMember = new EsamMembers();
    $selected = cleanup($_POST['esamMainChar'], 64);

    if ($selected == "all") {
      $esamMember->removeMemberSetting($id_member, "PREFERRED_CHAR_ID");
    } else {
      $esamMember->setMemberSetting($id_member, "PREFERRED_CHAR_ID", $selected);
    }
  }

  if (isset($_POST['esamUserId']) && isset($_POST['esamApiKey'])) {
    $api_key = cleanup($_POST['esamApiKey'], 64);
    $user_id = cleanup($_POST['esamUserId'], 8);

    $esamValidator = new EsamValidator();
    if ($esamValidator->checkUserAndKey($user_id, $api_key)) {
    // Save it
      $esamMembers = new EsamMembers();
      $esamMembers->saveEveUserData($id_member, $user_id, $api_key);
      // then give them MemberGroups based on the rules
      $esamValidator->validateApiKeys($id_member);
    }
    else {
      $esamGlobal = new EsamGlobal();
      if ( allowedTo('admin_forum') ) {
        $esamMembers = new EsamMembers();
        if (empty($api_key) && empty($user_id)) {
          $esamMembers->removeEveUserData($id_member);
        }
        else {
          $esamMembers->saveEveUserData($id_member, $user_id, $api_key);
        }
      }
      else if ( $esamGlobal->getGlobalSetting("GLOBAL_REQUIRED_API", "false") == "true") {
          fatal_error("Invalid API key, click back and re-enter a valid API key.", false);
        }
    }
  }
}

function verifyApiKey($user_id, $api_key) {
  $esamValidator = new EsamValidator();
  if (!$esamValidator->checkUserAndKey($user_id, $api_key)) {
    fatal_error("Invalid API key, click back and re-enter a valid API key.", false);
  }
}

function saveAndValidate($member_id, $user_id, $api_key) {
  $esamMember = new EsamMembers();
  $esamMember->saveEveUserData($member_id, $user_id, $api_key);

  $esamValidator = new EsamValidator();
  $esamValidator->validateApiKeys($member_id);
}
?>
